<template>
<div class="shop_qx">
<scroll ref="scroll"
              :data="cartProducts"
              :scrollbar="scrollbarObj"
              :pullUpLoad="pullUpLoadObj"
              :startY="parseInt(startY)"
							:pos="'top:-0px'"
              @pullingUp="onPullingUp"
							>
  <div class="confirm-order" slot="content">
     <group v-if="orderType==2">
       <datetime :value="date" format="HH:mm" :min-hour=getHous :max-hour=23 :minute-list="['00','05','10','15','20','25','30','35','40','45','50','55']" @on-change="change"  :title="typeTitle" ref="date"></datetime>
        <span style="color: red;font-size:14px;padding:0rem .6rem;"><span style="padding-right:.2rem;">*</span>一小时之内未取餐系统自动确认收货</span>
      </group>
      <!-- 台桌号 -->
      <div class="weui-cell vux-tap-active weui-cell_access" style="font-size: 0.46rem; padding: 0.5rem;background-color:#fff;" v-else>
        <div class="weui-cell__hd"></div>
        <div class="vux-cell-bd vux-cell-primary">
          <p><label class="vux-label" style="font-weight: 600;color: #000;">台桌号</label> </p> 
          <span class="vux-label-desc"></span>
        </div>
        <div class=""> 
          <p >{{tableName}}</p> 
        </div>
      </div>
      <!-- 订单详情 -->
      <group class="order_bg">
        <group-title slot="title" class="order-details">订单详情
        </group-title>
        <cell-box>
          <ul>
            <li v-for="(item,key) in cartProducts" :key="key">
              <span style="-webkit-flex:1;">{{item.name}}</span>
              <span style="-webkit-flex:1;">x{{item.num}}</span>
              <span>￥{{item.price*item.num}}</span>
            </li>
          </ul>
        </cell-box>
        <cell-box class="order-total">
          <p><strong>合计:</strong></p>
          <p>￥{{total}}</p>
        </cell-box>
      </group>
      <group>
        <popup-picker :title="'用餐人数'" :data="numbers" :value="num1"  @on-change="setNum"  :placeholder="'必选'"  style=" font-size:0.46rem; padding:0.2rem 0rem;" v-if="orderType ==1"></popup-picker>
        <!-- 隐藏 -->
        <!-- <cell is-link title="口味偏好:"  style=" font-size:0.46rem; padding:0.5rem;" link="/goods/confirOrder/remark">
          <p>{{remarkText||inputText? remarklist: ''}}</p> 
        </cell> -->
      </group>
      <group>
        <x-input  title="联系号码:" name="mobile" class="weui-vcode" placeholder="请输入手机号码" v-model="phone" keyboard="number" is-type="china-mobile" :max="13">
        </x-input>
      </group>
      <group>
        <cell title="优惠券" :value="couponName" is-link @click.native="showPopup=true" v-if="couponName"></cell>
      </group>
      <!--<div v-transfer-dom>
        <popup v-model="showPopup" class="checker-popup" style="background:#fff;">
            <checker
            default-item-class="demo4-item"
            selected-item-class="demo4-item-selected"
            style="height:150px;display:flex;flex-direction:column"
            >
              <checker-item  :value="item.id" @on-item-click="onItemClick(item)" v-for="(item,index) in coupoList" :key="index" > {{ item.name }} </checker-item>
            </checker>
        </popup>
      </div> -->
  </div>
</scroll>
<div v-transfer-dom>
  <popup v-model="showPopup" class="checker-popup" style="background:#fff;">
      <checker
        default-item-class="demo4-item"
        selected-item-class="demo4-item-selected"
        style="height:150px;display:flex;flex-direction:column"
        >
        <checker-item  :value="item.id" @on-item-click="onItemClick(item)" v-for="(item,index) in coupoList" :key="index" > {{ item.name }} </checker-item>
      </checker>
    </popup>
  </div>
  <section class="submit-order">
    <p>¥{{total}}</p>
    <p @click="confrimOrder">{{orderType==='2'?'下单支付':'下单预定'}}</p>
  </section>
</div>
</template>
<script>
import {Group, CellBox,  GroupTitle, Cell, Picker,PopupPicker,Popup,Datetime, TransferDomDirective as TransferDom,Checker, CheckerItem,XInput} from 'vux'
import { mapState,mapGetters,mapActions,mapMutations} from 'vuex'
import {getStore} from '@/config/mUtils'
import {removeStore} from '@/config/mUtils'
import _ from 'lodash'
import Scroll from 'components/scroll/scroll.vue'
let numbers = []
for(let i = 1; i<40; i++){
  numbers.push({
    name: i+'人',
    value: i+''
  })
}
const mydate = new Date()
export default {
  directives: {
    TransferDom
  },
  components: {
    Group,
    CellBox,
    GroupTitle,
    Cell,
    Picker,
    PopupPicker,
    Datetime,
    Checker,
    CheckerItem,
    XInput,
    Scroll,
    Popup
  },
  created(){
    this.total = this.$route.query.total //总价
    this.tableName = this.$route.query.tableName //台桌号
    this.tableId = this.$route.query.tableId //台桌id
    this.openId = this.$route.query.openId //  openId
    this.shopId = this.$route.query.shopId
    this.shopName = this.$route.query.shopName
    this.orderType = this.$route.query.orderType //是否扫码 还是直接进店   1 为扫码 2为直接进店
    this.type = this.$route.query.type
    // 刷新人数归零
    this.setNum(0)
    if(this.type=='1'){
        this.typeTitle="取餐时间"
    }
    else if(this.type=='2'){
        this.typeTitle="入住时间"
    }
    else if(this.type=='3'){
        this.typeTitle="游玩时间"
    }
    else if(this.type=='4'){
        this.typeTitle="取货时间"
    }
    // 优惠券
    if(Object.keys(this.coupon).length !== 0){
      if(this.coupon.bestCoupon){
        this.couponName = this.coupon.bestCoupon.name;
        this.couponId = this.coupon.bestCoupon.id;
      }
      if(this.coupon.coupons.length >0){
        this.coupoList = this.coupon.coupons;
      }
    }
    this.phone =this.cellphone
  },
  data () {
    return {
      numbers: [numbers],
      total: 0,
      tableId: null,
      tableName: null,
      openId: null,
      orderType: null,
      shopId: null,
      shopName: null,
      date: mydate.getMinutes()>55 ? `${mydate.getHours()}:${mydate.getMinutes()}` : `${mydate.getHours()}:${mydate.getMinutes()+5}`,
      // date: '现在',
      getHous: mydate.getHours(),
      type:null,
      typeTitle:null,
      couponName: '', //卡券名称
      couponId: '', //卡券id
      coupoList: [], //卡券列表
      showPopup: false,
      phone: '',
      page: 0,
      scrollbar: true,
      scrollbarFade: true,
      pullUpLoad: true,
      pullUpLoadThreshold: 0,
      pullUpLoadMoreTxt: '上拉加载更多数据',
      pullUpLoadNoMoreTxt: '没有更多数据了',
      startY: 0
    }
  },
  methods: {
    ...mapActions([
      'setNum'
    ]),
    ...mapMutations([
      'CLEAR_CART'
    ]),
    onItemClick (value) {
      this.couponName = value.name
      this.couponId = value.id
      this.showPopup = false
    },
    confrimOrder () {
      var _this = this;
      let num = this.num1[0]
      // 判断是否存在订单
      if(this.cartProducts){
        // 判断支付类型是否微信支付或是线下支付
        if(this.orderType === '2'){
          // 判断是否取餐时间为空
          if(this.isEmpty(this.date,'请选择正确的'+this.typeTitle) && this.isPhone(this.phone)){
            let data = {
              items: this.cartProducts,
              openId:this.openId,
              cellphone: this.phone,
              couponId: this.couponId,
              shopId: this.shopId,
              shopName: this.shopName,
              getTime: this.date
            }
            if(getStore('bindMobile') === '0'){
              this.$vux.confirm.show({
                title: '手机号码没有绑定',
                content: '请先绑定手机号码',
                onCancel () {
                  // console.log('err')
                },
                onConfirm () {
                  _this.$router.push({path:'/me/bindMobile',query:{phone:_this.phone}})
                }
              });
            }else if(getStore('bindMobile') === '1'){
              this.$http.post('order/createWx',data)
              .then(({data})=>{
                if(data.status === '200'){
                  this.$wechat.chooseWXPay({
                      timestamp: data.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                      nonceStr: data.data.nonceStr, // 支付签名随机串，不长于 32 位
                      package: `prepay_id=${data.data.prepay_id}`, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                      signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                      paySign: data.data.sign, // 支付签名
                      success: function (res) {
                        _this.CLEAR_CART();
                        // _this.$http.post(`cart/shop/${_this.shopId}/user/${_this.openId}/delete/`)
                        // .then(({data})=>{
                        //   this.$vux.toast.show({
                        //     type: 'success',
                        //     text: '已清空购物车',
                        //     time: 2000
                        //     })
                        // }).catch(err=>{
                        //   this.$vux.toast.show({
                        //     type: 'warn',
                        //     text: '购物车清空失败',
                        //     time: 2000
                        //   })
                        // })
                        _this.$router.push({path:'/order'});
                      }
                  });
                }
              }).catch(err=>{
                this.$vux.toast.show({
                  type: 'warn',
                  text: '支付失败',
                  time: 2000
                })
              }) 
            }
          }
          // else{
          //   this.$vux.toast.show({
          //     type: 'warn',
          //     text: '请选择正确的'+_this.typeTitle,
          //     time: 2000
          //   })
          // }
          
        }
        // 线下支付
        if(this.orderType === '1'){
          if(this.isEmpty(num,'人数不能为空') && this.isPhone(this.phone)){
            let data = {
              items: this.cartProducts,
              openId:this.openId,
              peopleNum: num,
              couponId: this.couponId,
              shopId: this.shopId,
              shopName: this.shopName,
              tableName: this.tableName,
              tableNo: this.tableId,
              cellphone: this.phone
            }
            if(getStore('bindMobile') === '0'){
              this.$vux.confirm.show({
                title: '手机号码没有绑定',
                content: '请先绑定手机号码',
                onCancel () {
                  // console.log('err')
                },
                onConfirm () {
                  _this.$router.push({path:'/me/bindMobile',query:{phone:_this.phone}})
                }
              });
            }else if(getStore('bindMobile') === '1'){
              this.$http.post('order/create',data)
              .then(({data})=>{
                if(data.status === '200'){
                  _this.CLEAR_CART();
                  // _this.$http.post(`cart/shop/${_this.shopId}/user/${_this.openId}/delete/`)
                  //   .then(({data})=>{
                  //     this.$vux.toast.show({
                  //       type: 'success',
                  //       text: '已清空购物车',
                  //       time: 2000
                  //     })
                  //   }).catch(err=>{
                  //     this.$vux.toast.show({
                  //       type: 'warn',
                  //       text: '购物车清空失败',
                  //       time: 2000
                  //     })
                  // })
                  _this.$router.push({path:'/order'});
                }
              }).catch(err=>{
                this.$vux.toast.show({
                  type: 'warn',
                  text: '支付失败',
                  time: 2000
                })
              })
            }
          }
        }
      }else{
        this.$vux.toast.show({
          type: 'warn',
          text: '订单不存在',
          time: 2000
        })
      }
    },
    change(val){
      if(mydate.getHours() < 10){
        if(mydate.getMinutes() < 10){
          if(val >= `0${mydate.getHours()}:0${mydate.getMinutes()}`){
            this.date = val
          }else if(val < `0${mydate.getHours()}:0${mydate.getMinutes()}`){
            this.$vux.toast.show({
              type: 'warn',
              text: '不能选择过去时间',
              time: 2000
            })
            this.date = ''
          }
        }else{
          if(val >= `0${mydate.getHours()}:${mydate.getMinutes()}`){
            this.date = val
          }else if(val < `0${mydate.getHours()}:${mydate.getMinutes()}`){
            this.$vux.toast.show({
              type: 'warn',
              text: '不能选择过去时间',
              time: 2000
            })
            this.date = ''
          }
        }
      }else{
        if(val >= `${mydate.getHours()}:${mydate.getMinutes()}`){
            this.date = val
        }else if(val < `${mydate.getHours()}:${mydate.getMinutes()}`){
          this.$vux.toast.show({
            type: 'warn',
            text: '不能选择过去时间',
            time: 2000
          })
          this.date = ''
        }
      }
    },
    //验证手机号码和是否为空
		isPhone(phone){
			// let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      // alert(reg.test(phone)) 
			if(!_.trim(phone)){
				this.$vux.toast.show({
					type: 'warn',
					text: '手机号码不能为空',
					time: 2000
				})
			}else{
        // return true
				if(this.phone.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/)){
					// this.$vux.toast.show({
					// 	type: 'warn',
					// 	text: '手机号码不正确',
					// 	time: 2000
					// })
          return true
				}else{
          this.$vux.toast.show({
						type: 'warn',
						text: '手机号码不正确',
						time: 2000
					})
          return false
					// return true
				}
			}
		},
    isEmpty(num,str){
			if(!_.trim(num)){
				this.$vux.toast.show({
					type: 'warn',
					text: str,
					time: 2000
				})
			}else{
				return true
			}
		},
		onPullingUp() {
      this.page++
    },
    rebuildScroll() {
      this.$nextTick(() => {
        this.$refs.scroll.destroy()
        this.$refs.scroll.initScroll()
      })
    },
  },
  computed: {
    ...mapState({
      // remarkText: state => state.shop.remarkText,
      // inputText: state => state.shop.inputText,
      num1: state=> state.shop.num1,
      coupon: state=> state.shop.coupon,
      cellphone: state=> state.app.cellphone
    }),
    ...mapGetters([
      'cartProducts'
    ]),
    scrollbarObj: function () {
      return this.scrollbar ? {fade: this.scrollbarFade} : false
    },
    pullUpLoadObj: function () {
      return this.pullUpLoad ? {
        threshold: parseInt(this.pullUpLoadThreshold),
        txt: {more: this.pullUpLoadMoreTxt, noMore: this.pullUpLoadNoMoreTxt}
      } : false
    }
    // 计算截取说明文字字符串
    // remarklist (){
    //   let str = new String;
    //   if (this.remarkText) {
    //     Object.values(this.remarkText).forEach(item => {
    //         str += item[1] + '，';
    //     })
    //     if(str.length > 10) {
    //       return str.substring(0, 10 * 2 - 10) + "...";
    //     }
    //   }
    //     //是否有自定义备注，分开处理
    //     if (this.inputText) {
    //         str += this.inputText;
    //         if(str.length > 10) {
    //           return str.substring(0, 10 * 2 - 10) + "...";
    //         }
    //     } else {
    //       return str.substr(0, str.lastIndexOf('，')) ;
    //     }
    // }
  },
  watch:{
		page(){
			// console.log('ss')
		},
		scrollbarObj: {
      handler() {
        this.rebuildScroll()
      },
      deep: true
    },
    pullUpLoadObj: {
      handler() {
        this.rebuildScroll()
      },
      deep: true
    },
    startY() {
      this.rebuildScroll()
    },
	},
}
</script>
<style scoped>
.change_show_type{
  display:flex;
  background-color:#fff;
  padding:.4rem 0;
}
.demo4-item {
  padding:10px;
  margin-top:15px;
  color: #222;
  text-align: center;
  font-size: 14px;
  line-height: 18px;
  border-bottom: 1px solid #ccc;
}
.demo4-item-selected {
  color: #2e9670;
}
.demo4-item-disabled {
  color: #999;
}
.change_show_type div{
  width: 100%;
  display: flex;
  align-content: center;
}
.change_show_type div .icon-more{
  flex: 1;
  color:#000; 
  font-weight:700;
  text-align: right;
  margin-right: 0.3rem;
}
.change_show_type div .tab_num{
  flex: 9;
  font-size: 0.5rem;
  font-weight: 600;
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
}
.change_show_type div .activity_show{
  color:#3190e8;
  border-color:#3190e8
}
.order_bg{
  background-color: #fff;
  width: 100%;
}
.order-details{
  text-align: left;
  color: #000;
  font-size: .46rem;
  font-weight: 600;
  padding: .44rem 0.4rem 0.44rem 0;
  margin-left: 0.4rem;
}
ul{
  width: 100%;
}
ul > li {
  padding: .2rem .3rem;
  display: flex;
   flex-wrap: nowrap; 
   justify-content: space-between; 
   font-size: 0.46rem;
}
.confirm-order .order-total{
  justify-content: space-between;
  padding: 0.42rem 0.56rem;
}
  .order-total p:nth-child(1){
  font-size: 0.46rem;
  font-weight: 700;
}
.order-total p:nth-child(2){
  font-size: 0.56rem; 
 }  
.submit-order{
  display:-webkit-flex;
  position:fixed;
  bottom:0;
  width:100%;
  height: 1.65rem;
  z-index: 999;
}
.submit-order p{
  line-height:1.6rem;
  font-size:.6rem;
  color:#fff
}
.submit-order p:nth-of-type(1){
  background-color:#fff;
  color: #000;
  flex:5;
  padding-left:.5rem;
  font-size: 0.64rem;
  font-weight: 700;
  text-align: left;
}
.submit-order p:nth-of-type(2){
  font-size: 0.46rem;
  flex:2.2;
  background-color:#2e9671;
  text-align:center
}
</style>
